package com.recyclerviewdemo.Fragment;


import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.recyclerviewdemo.Listener.RecyclerViewClickListener;
import com.recyclerviewdemo.R;
import com.recyclerviewdemo.Services.NetWork;
import com.recyclerviewdemo.adapters.RecyclerviewAdapter;
import com.recyclerviewdemo.entity.GankResult;

import java.util.List;

import rx.Observable;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func2;
import rx.schedulers.Schedulers;

/**
 * Created by Yang on 2016/9/5.
 */
public class FuLiFragment extends Fragment {

    private View mRootView;

    private RecyclerView recycler_view;
    private SwipeRefreshLayout swipe;
    private int contentQuantity = 20;
    private List<GankResult.ResultsBean> picData;
    private RecyclerviewAdapter mAdapter;
    private boolean mIsFirstTimeTouchBottom = true;
    private StaggeredGridLayoutManager layoutManager;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (mRootView == null) {
            mRootView = inflater.inflate(R.layout.activity_gank, container, false);
        }
        ViewGroup parent = (ViewGroup) mRootView.getParent();
        if (parent != null) {
            parent.removeView(mRootView);
        }

        initView();
        initData();

        return mRootView;
    }

    private void initView(){
        recycler_view = (RecyclerView)mRootView.findViewById(R.id.recycler_view);
        swipe = (SwipeRefreshLayout)mRootView.findViewById(R.id.swipe);
    }

    private void initData() {

        try {
            layoutManager = new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL);
            mAdapter = new RecyclerviewAdapter(getActivity());

            recycler_view.setAdapter(mAdapter);
            recycler_view.setLayoutManager(layoutManager);
            recycler_view.addOnScrollListener(getOnBottomListener(layoutManager));

            getNetData(false); //刚进入界面先刷新一次

            //调用RecyclerView#addOnItemTouchListener方法能添加一个RecyclerView.OnItemTouchListener对象
            recycler_view.addOnItemTouchListener(new RecyclerViewClickListener(getActivity(), new RecyclerViewClickListener.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position) {
                    Toast.makeText(getActivity(), "Click " + picData.get(position).getDesc(), Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onItemLongClick(View view, int position) {
                    Toast.makeText(getActivity(), "Long Click " + picData.get(position).getWho(), Toast.LENGTH_SHORT).show();
                }
            }));

            //刷新时执行的事件
            swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh() {
                    getNetData(true);
                }
            });

        }catch (Exception e){
            Log.e("=====>initview", e.toString());
        }
    }


    //查询最后一个可见Item的下标
    public int findLastVisibleItemPosition() {
        int lastVisibleItemPosition = 0;
        lastVisibleItemPosition = layoutManager.getItemCount()-1;
        return lastVisibleItemPosition;
    }

    //刷新获取网络数据
    private void getNetData(boolean loadMore) {
        try {
            swipe.measure(View.MEASURED_SIZE_MASK, View.MEASURED_HEIGHT_STATE_SHIFT);
            swipe.setRefreshing(true);

            if (loadMore) contentQuantity = contentQuantity + 10;
            Observable.combineLatest(NetWork.getGankApi().getAllDate("福利", contentQuantity, 1), NetWork.getGankApi().getAllDate("休息视频", contentQuantity, 1),
                    new Func2<GankResult, GankResult, Void>() {
                        @Override
                        public Void call(GankResult PicResult, GankResult TextResult) {
                            picData = PicResult.getResults();
                            mAdapter.setPicData(PicResult.getResults());
                            mAdapter.setTextData(TextResult.getResults());
                            return null;
                        }
                    })

                    .subscribeOn(Schedulers.newThread())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<Void>() {
                        @Override
                        public void onCompleted() {
                            swipe.setRefreshing(false);
                        }

                        @Override
                        public void onError(Throwable e) {
                            Toast.makeText(getActivity(), R.string.network_error, Toast.LENGTH_SHORT).show();
                            swipe.setRefreshing(false);
                        }

                        @Override
                        public void onNext(Void aVoid) {
                            mAdapter.notifyDataSetChanged();
                        }
                    });
        }catch (Exception e){
            Log.e("---->getdata",e.toString());
        }
    }

    RecyclerView.OnScrollListener getOnBottomListener(final StaggeredGridLayoutManager layoutManager) {
        return new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView rv, int dx, int dy) {
                boolean isBottom =
                        layoutManager.findLastCompletelyVisibleItemPositions(new int[2])[1] >=
                                mAdapter.getItemCount() - 20;
                if (!swipe.isRefreshing() && isBottom) {
                    if (!mIsFirstTimeTouchBottom) {
                        swipe.setRefreshing(true);
                        getNetData(true);
                    } else {
                        mIsFirstTimeTouchBottom = false;
                    }
                }
            }
        };
    }
}
